<?php

/**
 * Description of Util
 *
 * @author HEO
 */
class Util {

	public static function app() {
		return Yii::app();
	}

	public static function user() {
		return Yii::app()->user;
	}

	public static function module($m){
		return Util::app()->getModule($m);
	}

	public static function language() {
		return Yii::app()->language;
	}

	public static function webroot() {
		return Yii::getPathOfAlias('webroot');
	}
 	public static function baseUrl() {
		return Yii::app()->baseUrl;
	}
	public static function themeUrl() {
		return  Yii::app()->theme->baseUrl;
	}
	public static function homeUrl() {
		return Yii::app()->homeUrl;
	}
	public static function hostUrl() {
		return "http://" . $_SERVER['HTTP_HOST'].self::baseUrl();
	}


	public static function baseUpload($folder = null) {
		return self::baseUrl() . '/uploads' . (($folder != '') ? ('/' . $folder) : '');
	}
	public static function pathUpload($folder = null) {
		return self::webroot() . '/uploads' . (($folder != '') ? ('/' . $folder) : '');
	}
	public static function baseTheme($folder = null) {
		return self::themeUrl() . (($folder != '') ? ('/' . $folder) : '');
	}
	public static function pathTemplateExcel($template = null) {
		return self::webroot() . '/data/templateExcel/' . $template. '.xls';
	}
	public static function pathDownload($template = null) {
		return self::webroot('temp') . '/' . $template;
	}


	public static function clientScript() {
		return Yii::app()->clientScript;
	}

	public static function registerScriptFile($url, $position = CClientScript::POS_HEAD) {
		Util::clientScript()->registerScriptFile($url, $position);
	}

	public static function registerScript($id, $script, $position = CClientScript::POS_READY) {
		Util::clientScript()->registerScript($id, $script, $position);
	}

	public static function registerCssFile($url, $media = '') {
		Util::clientScript()->registerCssFile($url, $media);
	}

	public static function registerCss($id, $css, $media='') {
		Util::clientScript()->registerCss($id, $css, $media='');
	}

	public static $arrayActive = array(1 => 'Kích hoạt', 0 => 'Vô hiệu');
	public static $arrayCofirm = array(1 => 'Yes', 0 => 'No');
	public static $event = array(0=>'Thông báo', 1=>'Thư mời');


	public static function getImageExist($folder, $imgNm) {
		$check = false;
		$path  = self::pathUpload($folder) . '/' . $imgNm;
		if (file_exists($path) && $imgNm != '')
			$pathView = self::baseUpload($folder) . '/' . $imgNm;
		else{
			if ($folder == 'avatar' || $folder == 'profile') {
				$pathView = self::baseUpload($folder) . '/no_avatar.png';
			}
			else {
				$pathView = self::baseUpload() . '/no_image.jpg';
			}
		}
		return $pathView;
	}

	public static function t($string, $params = array(), $category = 'Label') {
		Yii::import('application.modules.admin.models.Translate');

		$language = Yii::app()->language;
		$cache_id = sprintf('translations_%s_%s', $language, $category);

		$messages = false;
		if (Yii::app()->cache)
			$messages = Yii::app()->cache->get($cache_id);

		if ($messages === false) {
//			$translations = Translate::model()->findAll('category = :category AND language_code = :language', array(
//				':category' => $category,
//				':language' => $language
//					));
//			$messages = array();
//			foreach ($translations as $row) {
//				$messages[$row->message] = $row->translation;
//			}

			if (Yii::app()->cache)
				Yii::app()->cache->set($cache_id, $messages, Yii::app()->params['caching_time']);
		}

		if (isset($messages[$string]))
			return strtr($messages[$string], $params);
		else
			return strtr($string, $params);
	}

	public static function toAscii($str) {
		$str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
		$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
		$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
		$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
		$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
		$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
		$str = preg_replace("/(đ)/", 'd', $str);
		$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
		$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
		$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
		$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
		$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
		$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
		$str = preg_replace("/(Đ)/", 'D', $str);
		$str = ereg_replace("[-.,]", "", $str);
		$str = ereg_replace("[^ A-Za-z0-9]", " ", $str);
		return $str;
	}

	public static function searchCharUTF8 () {
		return array(
			'a' => "/(a|à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/",
			'e'	=> "/(e|è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/",
			'i'	=> "/(i|ì|í|ị|ỉ|ĩ)/",
			'o'	=> "/(o|ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/",
			'u'	=> "/(u|ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/",
			'y'	=> "/(y|ỳ|ý|ỵ|ỷ|ỹ)/",
			'd'	=> "/(d|đ)/",
			'A' => "/(A|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/",
			'E'	=> "/(E|È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/",
			'I'	=> "/(I|Ì|Í|Ị|Ỉ|Ĩ)/",
			'O'	=> "/(O|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/",
			'U'	=> "/(U|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/",
			'Y'	=> "/(Y|Ỳ|Ý|Ỵ|Ỷ|Ỹ)/",
			'D'	=> "/(D|Đ)/",
		);
	}

	public static function toAlias($str) {
		$str = self::toAscii($str);
		$word_list = split(' ', $str);
		$str = '';
		foreach ($word_list as &$word) {
			if ($word != '')
				$str .= '-' . $word;
		}
		return trim(strtolower(substr($str, 1, strlen($str))));
	}

	public static function getFileExtension($filename) {
		return strtolower(substr($filename, strpos($filename, '.') + 1));
	}

	public static function generalCode($lastID, $length = 4, $prefixChar = null) {
		if ($lastID != null) {
			$prefix = "";
			while (strlen($lastID) < $length) {
				$prefix .= 0;
				$lastID = $prefix . $lastID;
				$prefix = "";
			}

			return $prefixChar . $lastID;
		}
	}

	/**
	 * check user role
	 */
	public static function isAllowProcess($userID, $role, $controllerName, $controllerAction){
		if ($role == 'Administrator')
			return 1;
		else
//			$role = UserRole::model()->findAll(array(
//				'select' => 'controller_action',
//				'condition' => 'user_id = :userID AND controller_name = :controllerName AND role = :role AND controller_action = :controllerAction AND status = 1',
//				'params' => array(
//					':userID' => $userID,
//					':role' => $role,
//					':controllerAction' => $controllerAction,
//					':controllerName' => $controllerName
//				)
//			));
		return $role;
	}

//	public static function getUserRole($userID){
//		Yii::import('application.modules.admin.models.AuthAssignment');
//		$userRole = AuthAssignmentBase::model()->find(array(
//			'condition' => 'userid = :userID',
//			'params' => array(
//				':userID' => $userID
//			),
//		));
//
//		if ($userRole)
//			return $userRole->itemname;
//		else
//			return null;
//	}

	/**
	 * list all user except admin for create role access in UserRoleController
	 */
	public static function listUsers(){
		$users = User::model()->findAll(array(
			'select' => 't.id, CONCAT(profile.lastname,\' \', profile.firstname) as fullname',
			'join' => 'JOIN profile ON profile.user_id = t.id JOIN auth_assignment ON auth_assignment.userid = t.id',
			'condition' => 'auth_assignment.itemname <> \'Administrator\''
		));

		return CHtml::listData($users, 'id', 'fullname');
	}

	/**
	 * list all role name
	 */
//	public static function listRolesName(){
//		$role = User::model()->findAll(array(
//			'select' => 'auth_assignment.itemname',
//			'join' => 'JOIN auth_assignment ON  auth_assignment.userid = t.id',
//			'condition' => 'auth_assignment.itemname <> \'Administrator\'',
//		));
//
//		return CHtml::listData($role, 'itemname', 'itemname');
//	}

	/**
	 * Get User fullname by is
	 */
	public static function userFullNameByID($id){
		Yii::import('application.modules.user.models.Profile');
		$model = $model = Profile::model()->findByPk($id);

		if($model === NULL)
			return Util::t("Null Value");

		return CHtml::link($model->lastname." ".$model->firstname, Yii::app()->createUrl('user/admin/view', array('id' => $model->user_id)), array('target' => '_blank'));
	}

	public static function getImageName($image){
			$imgNm = preg_replace('/\/|™|®|©|\s|\'|-/', '_', $image);
			return $imgNm;
	}
	/**
	 * Return admin status.
	 * @return boolean
	 */
	public static function isAdmin() {
		return Yii::app()->getModule('user')->isAdmin();
	}

	/**
	 * Return mod status.
	 * @return boolean
	 */
	public static function isSuperMod() {
		return Yii::app()->getModule('user')->isSuperMod();
	}

	/**
	 * Return member status.
	 * @return boolean
	 */
	public static function isMember() {
		return Yii::app()->getModule('user')->isMember();
	}

	/**
	 * Return member not active.
	 * @return boolean
	 */
	public static function isRegister() {
		return Yii::app()->getModule('user')->isRegister();
	}

	/**
	 * Return admins.
	 * @return array syperusers names
	 */
	public static function getAdmins() {
		return Yii::app()->getModule('user')->getSuperUsers('administrator');
	}

	/**
	 * Get User fullname by is
	 */
	public static function getUserName($id = ""){
		$id = $id == "" ? Yii::app()->user->id : $id;
		if (self::isSuperMod()) {
			Yii::import('application.models.Profiles');
			$model 	= Profiles::model()->findByPk($id);
			$name 	= (isset($model)) ? $model->fullname : NO_NAME;
		}
		else {
			Yii::import('application.models.Member');
			$model 	= Member::model()->findByPk($id);
			$name 	= (isset($model)) ? $model->fullname : NO_NAME;
		}
		return self::formatFullName($name);
	}

	/*
	 * getRegister
	 */
	public static function getRegister() {
		return Yii::app()->getModule('user')->getRegister('register');
	}


	/*
	 * getSuperMods
	 */
	public static function getSuperMods() {
		return Yii::app()->getModule('user')->getSuperUsers();
	}

	/*
	 * getMember
	 */
	public static function getMember() {
		return Yii::app()->getModule('user')->getMember();
	}

	/*
	 * encrypting
	 */
	public static function encrypting($str) {
		$hash = HASH;
		if ($hash=="md5")
			return md5($str);
		if ($hash=="sha1")
			return sha1($str);
		else
			return hash($hash,$str);
	}

	/*
	 * itemAlias
	 */
	public static function itemAlias($type,$code=NULL) {
		$_items = array(
			'Sex'	=> array(
				SEX_GIRL => TITLE_GIRL,
				SEX_BOY => TITLE_BOY,
			),
			'Status' => array(
				STATUS_NOACTIVE => 'Vô hiệu',
				STATUS_ACTIVE => 'Kích hoạt',
			),
			'UserStatus' => array(
				STATUS_NOACTIVE => 'Vô hiệu',
				STATUS_ACTIVE => 'Kích hoạt',
//				STATUS_BANNED => UserModule::t('Banned'),
			),
			'CheckType' => array(
				''				=> '',
				STATUS_ACTIVE 	=> 'Có',
				STATUS_NOACTIVE => 'Không',
			),
			'AdminStatus' => array(
				STATUS_NOACTIVE => 'Không',
				STATUS_ACTIVE => 'Có',
			),
			'Event' => array(
				STATUS_NOACTIVE => 'Thông báo',
				STATUS_ACTIVE => 'Thư mời',
			),
			'Finish' => array(
				'0' => 'Không nhận',
				'1' => 'Đang nhận',
				'2' => 'Đã nhận',
				'3'	=> 'Không hoàn thành'
			),
			'Scholarship' => array(
				'0' => 'Không nhận',
				'1' => 'Đang nhận',
			),
			'EvenJoin' => array(
				'0' => 'Không phản hồi',
				'1' => 'Có tham dự',
				'2' => 'Không tham dự',
			),
			'ViewComment' => array(
				'0' => 'Chưa xem',
				'1' => 'Đã xem',
			),
			'CheckComment' => array(
				'1' => 'Hợp lệ',
				'0' => 'Không hợp lệ',
			),
		);
		if (isset($code))
			return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
		else
			return isset($_items[$type]) ? $_items[$type] : false;
	}

	/*
	 * formatFullName
	 */
	public static function formatFullName($name, $lower = false) {
		$fullname = trim($name);

		if ($fullname != '') {
			$fullname	= preg_replace('/\s\s+/', ' ', $fullname);
			$fullname 	= mb_strtolower($fullname, ENDCODE);
			if ($lower === false) {
				$fullname	= mb_convert_case($fullname, MB_CASE_TITLE, ENDCODE);
			}
		}
		return $fullname;

	}

	/*
	 * formatPhone
	 */
	public static function formatPhone($phone, $forShow = true) {
		if ($phone != '') {
			if ($forShow === true) {
				$phoneLength = mb_strlen($phone);
				if ($phoneLength > 7) {
					$phone = number_format($phone, 0, " ", " ");
				}
				else {
					$phone = '(08) ' . $phone;
				}
			}
			else {
				$phone = preg_replace("/[^0-9]/", "", $phone);
			}
		}
		return $phone;
	}

	/*
	 * formatTime
	 */
	public static function formatTime($time, $full = true, $slash = '/', $visit = false) {
		if ($time != '') {
			if ( $time == '0000-00-00 00:00:00') {
				if ($visit)
					$time = NEVER_LOGIN;
				else
					$time = str_replace('-', $slash, $time);
			}
			else {
				$match 	= "d{$slash}m{$slash}Y" . (($full) ? ' H:i:s' : null);
				$time 	= date($match, strtotime($time));
			}
		}
		return $time;
	}

	/*
	 * getAge
	 */
	public static function getAge($birthDate) {
		$age = null;
		if ($birthDate != null) {
			$birthDate	= preg_replace('[-]', '/', $birthDate);
			$birthDate  = explode("/", $birthDate);
			//get age from date or birthdate
			$age 	= (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])):(date("Y")-$birthDate[2]));

			$age	= (intval($age) > 0) ? $age : null;
		}

		return $age;
	}

	/*
	 * getPaggingIndex
	 */
	public static function getPaggingIndex($page = 1) {
		$pageIndex 	= 1;
		$page 		= (isset($_GET["SuperMod_page"])) ? $_GET["SuperMod_page"] : 1;
		if ($page > 1) {
			$pageIndex = (($page - 1) * PAGE_SIZE) + 1;
		}
		return intval($pageIndex);
	}

	/*
	 * markSearch
	 */
	public static function markSearch($model,$field, $value = '##FALSE##',$prefix='<strong>',$sufix='</strong>') {
		$className 		= get_class($model);
		$value			= ($value === '##FALSE##') ? $model->getAttribute($field) : $value;

		if (isset($_GET[$className][$field])&&$_GET[$className][$field]){
			$key = $patterns = $replace = $_GET[$className][$field];
//			$arrCharUtf8	= self::searchCharUTF8();
//			if (array_key_exists($key, $arrCharUtf8)){
//				$patterns 	= $arrCharUtf8[$key];
//				$replace 	= "$1";
//			}

			return str_replace($patterns, $prefix.$replace.$sufix, $value);

		}
		else
			return $value;
	}
	public static function generalUserName() {
		return 'temp' . date('ymdHis');
	}
	public static function generalPass() {
		return substr(md5(rand()),0,rand(8, 10));
	}
	public static function generalMemberCode($status, $course_id) {
		Yii::import('application.modules.member.models.Member');
		$code = null;
		if ($status != null && $course_id != null) {
			$code = $status . mb_substr($course_id, 2, 2);

			// Get max number record
			$result  	= Member::model()->countMember($course_id);
			$maxIndex	= (isset($result) && is_numeric ($result->max_code)) ? $result->max_code : 0;
			$maxIndex	= $maxIndex + 1;
			$code		.= self::generalCode($maxIndex, 3);

		}
		return $code;
	}
	public static function getDataFromModel($model = null, $field = '', $type = 1){
		$return  = null;
		if (isset($model)) {
			foreach ($model as $data) {
				if ($type == '1') {
					$return[$data->$field] = $data->$field;
				}
			}
		}
		return $return;
	}

	/*
	 * convertDateToVN
	 */
	public static function convertDateToVN($datetime) {
		$date = explode("/", date("d/m/Y", strtotime($datetime)));
		$monthName = array(	1 => " Tháng Một ",
							2 => " Tháng Hai ",
							3 => " Tháng Ba ",
							4 => " Tháng Bốn ",
							5 => " Tháng Năm ",
							6 => " Tháng Sáu ",
							7 => " Tháng Bảy ",
							8 => " Tháng Tám ",
							9 => " Tháng Chín ",
							10 => " Tháng Mười ",
							11 => " Tháng Mười Một ",
							12 => " Tháng Mười Hai ",
							);
		$dateStr = $date[0] . $monthName[ltrim($date[1], "0")] . $date[2];
		return $dateStr;
	}

	/*
	 * getUserComment
	 */
	public static function getUserComment($data) {
		$name = NO_NAME;
		if($data->user_id != '' && isset($data->user)) {
			if(($data->user->superuser == MEMBER || $data->user->superuser == REGISTER))
				$name = (isset($data->user->member)) ? $data->user->member->fullname : NO_NAME;
			else
				$name = (isset($data->user->profile)) ? $data->user->profile->fullname : NO_NAME;
		}

		return self::formatFullName($name);
	}

	/*
	 * getListModule
	 */
	public static function getListModule(){
		return array_keys(Yii::app()->getModules());
	}
	/*
	 * getSemesterInfo
	 */
	public static function getSemesterInfo($education) {
		$arrSemesters = $arrSubjects = array();
		if (isset($education)) {
			if (isset($education->semester)) {
				$i = 0;
				foreach ($education->semester as $semester) {
					$arrSemesters[$i] = $semester->attributes;
					if (isset($semester->subjects)) {
						foreach ($semester->subjects as $subject) {
							$arrSubjects[$i][] = $subject->attributes;
						}
					}
					$i++;
				}
			};
		}
		return array($arrSemesters, $arrSubjects);
	}

	/*
	 * getEducationInfo
	 */
	public static function getEducationInfo($listCodes = null, $getTrash = true) {
		$codeActive = $codeTrash = $edutionActive = $edutionTrash = null;
		if (isset($listCodes)) {
			foreach ($listCodes as $code) {
				if ($code->active == 1) {
					$codeActive 	= $code;
					$edutions		= $code->educations;
					foreach ($edutions as $edution) {
						if ($edution->status == 1) {
							$edutionActive	= $edution;
						}
						else {
							$edutionTrash[]	= $edution;
						}
					}

					if (!$getTrash) {
						break;
					}
				}
				else {
					$codeTrash[]	= $code;
					$edutions		= $code->educations;
					foreach ($edutions as $edution)
						$edutionTrash[]	= $edution;
				}
			}
		}

		if ($getTrash)
			return array($codeActive,$codeTrash, $edutionActive, $edutionTrash);
		else
			return array($codeActive, $edutionActive);
	}

	/*
	 * getValueFromAlias
	 */
	public static function getValueFromAlias($value, $alias_name) {
		$aData = self::itemAlias($alias_name);
		return isset($aData[$value]) ? $aData[$value] : "Dữ liệu sai";
	}

	public static function sendMail($to,$from,$subject,$message){
		$mail=Yii::app()->Smtpmail;
		$mail->CharSet = 'utf-8';
		$mail->SetFrom($from, 'Hội khuyến học TPHCM');
		$mail->Subject	= $subject;
		$mail->MsgHTML($message);
		$mail->AddAddress($to, "");
		//return $mail->Send();
		if(!$mail->Send()) {
			//echo "Mailer Error: " . $mail->ErrorInfo;
			//return $mail->ErrorInfo;
			return false;
		}
		else {
			return true;
		}
	}

	public static function writeLogs ($file, $message, $flagNew = true) {
		$fileName = $file . "_" . date('Ymd') . '.txt';
		if (($fd = fopen($fileName, "a")) !== false) {
			if($flagNew) {
				fwrite($fd, "\r\n" . date("Y/m/d H:i:s") . ": ".$message."\n");
			}
			else {
				fwrite($fd, $message . "\n");
			}
			fclose($fd);
		}
	}
}
